package com.wstuo.common.security.action;

import java.io.Console;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.dto.CompanyDTO;
import com.wstuo.common.security.dto.EditUserPasswordDTO;
import com.wstuo.common.security.dto.LDAPAuthenticationSettingDTO;
import com.wstuo.common.security.dto.UserDTO;
import com.wstuo.common.security.dto.UserDetailDTO;
import com.wstuo.common.security.dto.UserQueryDTO;
import com.wstuo.common.security.dto.UserRoleDTO;
import com.wstuo.common.security.enums.SessionName;
import com.wstuo.common.security.service.IUserInfoService;
import com.wstuo.common.security.utils.AppContext;

/**
 * 用户Action类
 * 
 * @author will
 * 
 */
@SuppressWarnings("serial")
public class UserAction extends ActionSupport {
	private static final Logger LOGGER = Logger.getLogger(UserAction.class);
	private IUserInfoService userInfoService;
	private UserDTO userDto = new UserDTO();
	private List<UserRoleDTO> userRoleDto = new ArrayList<UserRoleDTO>();
	private UserQueryDTO userQueryDto = new UserQueryDTO();
	private Boolean result = false;
	private String info;//记录删除用户失败
	private PageDTO users;
	private Long[] ids;
	private Set<Long> setIds;
	private String sord;
	private String sidx;
	private int id;
	private int page = 1;
	private int rows = 10;
	private String str;
	private String userName;
	private String pwd;
	private String evenType; // 时间类型
	private String pageType; // 页面类型
	private String evenID; // 时间ID
	private String resultString;
	private String effect = "";
	private InputStream exportStream;
	private String fileName = "";
	private Long[] roleIds;
	private String[] userNames;
	private EditUserPasswordDTO editUserPasswordDTO;
	private String password;
	private CompanyDTO companyDTO;
	private Long companyNo;
	private UserDetailDTO userDetailDTO;
	private LDAPAuthenticationSettingDTO ldapAuthDTO;
	private String domainName;
	private int countTechnician;
	private Map<String, Object> resResultMap = new HashMap<String, Object>();
	private String[] res;
	private String dataFlag;
	private String email;
	private String state;
	private Boolean offlineResult = false;
	private int bl;
	@Autowired
	private AppContext appctx;
	
	public Boolean getOfflineResult() {
		return offlineResult;
	}

	public void setOfflineResult(Boolean offlineResult) {
		this.offlineResult = offlineResult;
	}
	
	

	public int getBl() {
		return bl;
	}

	public void setBl(int bl) {
		this.bl = bl;
	}

	public Set<Long> getSetIds() {
		return setIds;
	}

	public void setSetIds(Set<Long> setIds) {
		this.setIds = setIds;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getDataFlag() {
		return dataFlag;
	}

	public void setDataFlag(String dataFlag) {
		this.dataFlag = dataFlag;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getEvenType() {
		return evenType;
	}

	public void setEvenType(String evenType) {
		this.evenType = evenType;
	}

	public String getPageType() {
		return pageType;
	}

	public void setPageType(String pageType) {
		this.pageType = pageType;
	}

	public String getEvenID() {
		return evenID;
	}

	public void setEvenID(String evenID) {
		this.evenID = evenID;
	}

	public int getCountTechnician() {
		return countTechnician;
	}

	public void setCountTechnician(int countTechnician) {
		this.countTechnician = countTechnician;
	}

	public Long getCompanyNo() {
		return companyNo;
	}

	public void setCompanyNo(Long companyNo) {
		this.companyNo = companyNo;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String[] getUserNames() {
		return userNames;
	}

	public void setUserNames(String[] userNames) {
		this.userNames = userNames;
	}

	public String getEffect() {
		return effect;
	}

	public void setEffect(String effect) {
		this.effect = effect;
	}

	public InputStream getExportStream() {
		return exportStream;
	}

	public void setExportStream(InputStream exportStream) {
		this.exportStream = exportStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getResultString() {
		return resultString;
	}

	public void setResultString(String resultString) {
		this.resultString = resultString;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public IUserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(IUserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	public UserDTO getUserDto() {
		return userDto;
	}

	public void setUserDto(UserDTO userDto) {
		this.userDto = userDto;
	}

	public UserQueryDTO getUserQueryDto() {
		return userQueryDto;
	}

	public void setUserQueryDto(UserQueryDTO userQueryDto) {
		this.userQueryDto = userQueryDto;
	}

	public Boolean getResult() {
		return result;
	}

	public void setResult(Boolean result) {
		this.result = result;
	}

	public List<UserRoleDTO> getUserRoleDto() {
		return userRoleDto;
	}

	public void setUserRoleDto(List<UserRoleDTO> userRoleDto) {
		this.userRoleDto = userRoleDto;
	}

	public PageDTO getUsers() {
		return users;
	}

	public void setUsers(PageDTO users) {
		this.users = users;
	}

	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public String getSidx() {
		return sidx;
	}

	public void setSidx(String sidx) {
		this.sidx = sidx;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public Long[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(Long[] roleIds) {
		this.roleIds = roleIds;
	}

	public EditUserPasswordDTO getEditUserPasswordDTO() {
		return editUserPasswordDTO;
	}

	public void setEditUserPasswordDTO(EditUserPasswordDTO editUserPasswordDTO) {
		this.editUserPasswordDTO = editUserPasswordDTO;
	}


	public UserDetailDTO getUserDetailDTO() {
		return userDetailDTO;
	}

	public void setUserDetailDTO(UserDetailDTO userDetailDTO) {
		this.userDetailDTO = userDetailDTO;
	}

	public LDAPAuthenticationSettingDTO getLdapAuthDTO() {
		return ldapAuthDTO;
	}

	public void setLdapAuthDTO(LDAPAuthenticationSettingDTO ldapAuthDTO) {
		this.ldapAuthDTO = ldapAuthDTO;
	}

	public String getDomainName() {
		return domainName;
	}

	public void setDomainName(String domainName) {
		this.domainName = domainName;
	}

	public Map<String, Object> getResResultMap() {
		return resResultMap;
	}

	public void setResResultMap(Map<String, Object> resResultMap) {
		this.resResultMap = resResultMap;
	}

	public String[] getRes() {
		return res;
	}

	public void setRes(String[] res) {
		this.res = res;
	}

	public CompanyDTO getCompanyDTO() {
		return companyDTO;
	}

	public void setCompanyDTO(CompanyDTO companyDTO) {
		this.companyDTO = companyDTO;
	}
	

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	/**
	 * save user
	 * 
	 * @return String
	 */
	public String save() {
		userInfoService.saveUser(userDto);

		return SUCCESS;
	}

	/**
	 * search user
	 * 
	 * @return String
	 */
	public String find() {

		int start = (page - 1) * rows;
		userQueryDto.setStart(start);
		userQueryDto.setLimit(rows);
		if ("false".equals(state)) {
			userQueryDto.setUserState(false);
		} else if ("true".equals(state)) {
			userQueryDto.setUserState(true);
		} else {
			userQueryDto.setUserState(null);
		}
		users = userInfoService.findPagerUser(userQueryDto, sord, sidx);
		if (users != null) {
			users.setPage(page);
			users.setRows(rows);
		}
		return SUCCESS;
	}
	
	/**
	 * edit user
	 * 
	 * @return String
	 */
	public String merge() {
		userInfoService.editUser(userDto);

		return SUCCESS;
	}

	/**
	 * delete user
	 * 
	 * @return String
	 */
	public String delUser() {
		try {
			result = userInfoService.delUser(ids);
		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			if(sw.toString().contains("foreign key")){
				info="error";
				return "info";
			}else
				throw new ApplicationException("ERROR_DATA_CAN_NOT_DELETE", e);
		}

		return "result";
	}

	/**
	 * user role
	 * 
	 * @return String
	 */
	public String getUserRole() {
		userRoleDto = userInfoService.getUserRoleByUserId(id);

		return "userRoleDto";
	}

	/**
	 * updateRoleByUserId
	 * 
	 * @return String
	 */
	public String updateRoleByUserId() {
		userInfoService.mergeAllUser(ids, userDto.getRoleIds());

		return SUCCESS;
	}

	/**
	 * userExist
	 * 
	 * @return String
	 */
	public String userExist() {
		result = userInfoService.userExist(userDto.getLoginName());

		return "result";
	}

	/**
	 * 批量更新所属机构
	 * 
	 * @return update result
	 */
	public String mergeByOrg() {
		result = userInfoService.mergeByOrg(str, id);
		return "result";
	}

	/**
	 * 根据用户名查找用信息
	 * 
	 * @return user dto
	 */
	public String findByUserName() {
		userDto = userInfoService.findUserByName(userName);
		return "userDto";
	}

	/**
	 * 查询个人详细 wap端
	 * 
	 * @return user detail info
	 */
	public String findUserDetail_wap() {
		userDto = userInfoService.findUserByName(userName);
		
		return "userDto_wap";
	}
	
	/**
	 * 查看用户是否被禁
	 * 
	 * @return user disable status
	 */
	public String findDisable() {
		resultString = userInfoService.findDisable(userName, pwd);
		return "resultString";
	}

	/**
	 * 检验用户是否存在.
	 * 
	 * @return user validate result
	 */
	public String vaildateUserByIds() {
		result = userInfoService.vaildateUserByIds(userNames);
		return "result";
	}

	/**
	 * 根据用户全名验证用户是否存在
	 * 
	 * @return boolean
	 */
	public String vaildateUserByFullName() {
		result = userInfoService.findUserByFullNames(userNames);
		return "result";
	}

	/**
	 * 导出数据.
	 * 
	 * @return export inputStream
	 */
	public String exportUser() {
		exportStream = userInfoService.exportUserItems(userQueryDto, sord, sidx);
		return "exportFileSuccessful";
	}

	/**
	 * 导入数据
	 * 
	 * @return import result
	 */
	public String importUserData() {

		try {
			effect = userInfoService.importUserItems(userQueryDto.getImportFile());
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}

		return "importResult";
	}

	/**
	 * 修改密码
	 * 
	 * @return reset result true or false
	 */
	public String resetPassword() {
		result = userInfoService.resetPassword(editUserPasswordDTO);
		return "result";
	}

	/**
	 * 根据密码查看用户是否存在.
	 * 
	 * @return find result true or false
	 */
	public String findUserByPassword() {
		result = userInfoService.findUserByPassword(password);
		return "result";
	}

	/**
	 * 根据当前用户获取所在公司
	 * 
	 * @return organization dto
	 */
	public String findUserCompany() {
		companyDTO = userInfoService.findUserCompany(userName);
		return "defaultCompany";
	}

	/**
	 * 查询用户详细
	 * 
	 * @return user detail info
	 */
	public String findUserDetail() {
		userDetailDTO = userInfoService.findUserByUserIdAndLogName(userDto.getUserId(), userDto.getLoginName());
		return "userDetail";
	}

	/**
	 * 用户登录.
	 * 
	 * @return login result true or false
	 */
	public String userLogin() {

		result = userInfoService.userLogin(userName, password);
		return "result";
	}

	/**
	 * 获取当前用户信息.
	 * 
	 * @return user dto
	 */
	public String getCurrentLoginUser() {
		userDto = userInfoService.getCurrentLoginUser();
		return "userDto";
	}

	/**
	 * 根据用户名获取用户信息.
	 * 
	 * @return user dto
	 */
	public String getUserDetailByLoginName() {

		userDto = userInfoService.getUserDetailByLoginName(userName);
		return "userDto";
	}

	/**
	 * 根据电话号码获取用户
	 * 
	 * @return PageDTO
	 */
	public String findUserByNumber() {
		users = new PageDTO();
		users.setData(userInfoService.findUserByNumber(userQueryDto));

		return SUCCESS;
	}

	/**
	 * 自动登录
	 * 
	 * @return page url
	 */
	public String autoLogin() {

		ldapAuthDTO = userInfoService.autoLogin(userName, domainName);

		return "ldapAuthDTO";
	}

	/**
	 * 统计技术员数量.
	 * 
	 * @return count result
	 */
	public String countTechnician() {

		countTechnician = userInfoService.countTechnician();
		return "countTechnician";
	}

	/**
	 * LDAP验证并把用户加入到系统.
	 * 
	 * @return update result true or false
	 */
	public String ldapAuthAndUpdate() {
		result = userInfoService.ldapAuthAndUpdate(userName, password);
		return "result";
	}

	/**
	 * 用户资源验证
	 * 
	 * @return validate result
	 */
	public String findResAuthByUserName() {
		resResultMap = userInfoService.findResAuthByUserName(userName, res);
		return "resResultMap";
	}

	/**
	 * 验证登录名是否存在
	 * 
	 * @return boolean
	 */
	public String vaildateUserByLoginName() {
		result = userInfoService.findUserByLoginNames(userNames);
		return "result";
	}
	public String findUserByLoginName() {
		result = userInfoService.findUserByLoginName(userName);
		return "result";
	}
	
	/**
	 * 用户激活
	 * 
	 * @return activation result
	 */
	public String userActivation() {
		resultString = userInfoService.userActivation(userName, password, resultString);
		return "resultString";
	}

	/**
	 * 更新用户在线注册状态
	 * 
	 * @return update result
	 */
	public String updateOnLineRegisterStatus() {
		resultString = userInfoService.updateOnLineRegisterStatus(dataFlag, email);
		return "resultString";
	}

	/**
	 * 自动补全时验证用户是否存在
	 * 
	 * @return String
	 */
	public String autoVerification() {
		setIds = userInfoService.autoVerification(userDto.getFullName());
		return "setIds";
	}

	/**
	 * 根据打过来的电话去查询用户
	 * 
	 * @return userDto
	 */
	public String updateUserByPhone() {
		userDto = userInfoService.updateUserByPhone(userDto);
		return "userDto";
	}
	public String regByPhone(){
		userDto = userInfoService.saveUserByPhone(userDto);
		
		return "userDto";
	}
	/**
	 * 根据用户名修改用户手机号码
	 * 
	 * @return true or false
	 */
	public String findUserUpdatePhone() {
		result = userInfoService.findUserUpdatePhone(userDto);
		return "result";
	}

	/**
	 * 根据手机号码等信息新增用户
	 * 
	 * @return userDto
	 */
	public String saveuserByPhone() {
		userDto = userInfoService.saveUserByPhone(userDto);
		return "userDto";
	}

	/**
	 * 根据id查询
	 * 
	 * @return userDto
	 */
	public String findUserById() {
		userDto = userInfoService.findUserById(userDto);
		return "userDto";
	}


	/**
	 * 生成随机数
	 * 
	 * @return userDto
	 */
	public String setUserRandomId() {
		userDto = userInfoService.setUserRandomId(userDto);
		return "userDto";
	}

	/**
	 * 根据随机数查询用户
	 * 
	 * @return userDto
	 */
	public String findUserByRandomNum() {
		userDto = userInfoService.findUserByRandomNum(userDto);
		return "userDto";
	}

	/**
	 * 注销，清除Session
	 * 
	 * @return null
	 */
	public String loginOut() {
		appctx.invalidate();
		return null;
	}
	/**
	 * 根据用户名注销，清除Session
	 * 
	 * @return null
	 */
	@SuppressWarnings("unchecked")
	public String loginOutByLoginName() {
		HashMap<String, HttpSession> sessionMap = null;
		HttpSession session = null;
		if(ServletActionContext.getServletContext() != null){
			sessionMap = (HashMap<String, HttpSession>) ServletActionContext.getServletContext().getAttribute("sessionMap"); //获取服务器的session集合
			String loginName = userDto.getLoginName();		//获取前台传入的用户名
			if(sessionMap!=null&&sessionMap.containsKey(loginName)){
				session = sessionMap.get(loginName);
				sessionMap.remove(loginName);		//去除session集合中的用户
				ServletActionContext.getServletContext().setAttribute("sessionMap", sessionMap);//设置服务器的session集合
				session.invalidate();
				offlineResult = true;
			}
		}
		return "offlineResult";
	}
	public String changeEndUserStyle(){
		bl=userInfoService.changeEndUserStyle(userDto);
		return "bl";
	}
}
